package epg;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class Gen {

	private String filepath;
	private PrintWriter writer;
	private String fileName; // имя файла без расширения
	private String filePath; // полный путь
	private PrintStream sysout; // поток для вывода ошибок

	public Gen(String _filepath) {
		filepath = _filepath;
		File f = new File(filepath);
		filePath = f.getAbsolutePath();

		for (int i = 0; i < filePath.length(); i++) {
			if (filePath.charAt(i) == '.') {
				filePath = filePath.substring(0, i);
				break;
			}
		}

		// отделяем имя файла от расширения
		fileName = f.getName().substring(0, f.getName().indexOf('.'));

		filePath += ".java";

		writer = null;
		try {
			writer = new PrintWriter(new OutputStreamWriter(
			// new FileOutputStream(filePath), "windows-1251"));
					new FileOutputStream(filePath), "UTF-8"));
			sysout = new PrintStream(System.err, true, "UTF-8");
		} catch (Exception ex) {
		}
	}

	String getFileName() {
		return fileName;
	}

	void add(String str) {
		// System.out.println(str);
		print(str);
		if (writer != null)
			writer.write(str + "\n");
	}

	void print(String str) {
		if (sysout != null)
			sysout.println(str);
		// System.exit(1);
		// writer.close();
	}

	protected void finalize() {
		writer.close();
	}

	public void close() {
		if (writer != null)
			writer.close();
	}

}
